//
//  PlayerViewController.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 13-1-29.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "PlayerViewController.h"
#import "PlayerViewCell.h"

@interface PlayerViewController ()
{
    float length;
    float position;
}
@end

@implementation PlayerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlayerControll) name:kPlayerStateDidChange object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlayerProgress:) name:kAudioProgressDidChange object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playingIndexDidChange) name:kPlayerIndexDidChange object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(focus:) name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIImage *buttonImg = [[UIImage imageNamed:@"bar_button_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [focusButton setBackgroundImage:buttonImg forState:UIControlStateNormal];
    self.playingArray = [[AudioPlayer defaultPlayer] playlist];
    [playingTableView reloadData];
    
    titleLabel.text = [[[AudioPlayer defaultPlayer] currentItem] objectForKey:@"item_name"];
    
    [self playingIndexDidChange];
    [self updatePlayerControll];
    [self focus:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self focus:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _playingArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayerViewCell *cell = (PlayerViewCell *)[tableView dequeueReusableCellWithIdentifier:@"PlayerViewCell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"PlayerViewCell" owner:self options:nil] objectAtIndex:0];
    }
    cell.index = indexPath.row;
    cell.info = [_playingArray objectAtIndex:indexPath.row];
    [cell updateDisplay];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[AudioPlayer defaultPlayer] playIndex:indexPath.row];
}

- (IBAction)playAction:(id)sender
{
    [[AudioPlayer defaultPlayer] play];
}

- (IBAction)playLastAction:(id)sender
{
    [[AudioPlayer defaultPlayer] playPrevious];
}

- (IBAction)playNextAction:(id)sender
{
    [[AudioPlayer defaultPlayer] playNext];
}

- (IBAction)changeModeAction:(id)sender
{
    AudioPlayerMode playerMode = [[AudioPlayer defaultPlayer] playerMode] + 1;
    if (playerMode == AudioPlayerModeNum) {
        playerMode = AudioPlayerModeAllLoop;
    }
    [[AudioPlayer defaultPlayer] setPlayerMode:playerMode];
    [self updatePlayModeButton];
}

- (IBAction)seekTimeAction:(id)sender
{
    [[AudioPlayer defaultPlayer] playAtTime:playSlideView.value];
}

- (IBAction)slidingAction:(id)sender
{
    
    playedTimeLabel.text = [self stringFromSeconds:(int)length*playSlideView.value];
    remainTimeLabel.text = [NSString stringWithFormat:@"-%@",[self stringFromSeconds:(int)(length*(1-playSlideView.value))]];
}

- (void)updatePlayerControll
{
    switch ([[AudioPlayer defaultPlayer] playerState]) {
        case AudioPlayerStatePlaying:
            [playButton setBackgroundImage:[UIImage imageNamed:@"player_play_stop"] forState:UIControlStateNormal];
            break;
        case AudioPlayerStateStoped:
            [playButton setBackgroundImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
            break;
        case AudioPlayerStateNone:
            break;
        default:
            break;
    }
}

- (void)playingIndexDidChange
{
    lastButton.enabled = ([[AudioPlayer defaultPlayer] playingIndex] != 0);
    nextButton.enabled = ([[AudioPlayer defaultPlayer] playingIndex] != [[[AudioPlayer defaultPlayer] playlist] count] - 1);
    
    NSString *indexStr = [NSString stringWithFormat:@"%d/%d",[[AudioPlayer defaultPlayer] playingIndex] + 1,[[[AudioPlayer defaultPlayer] playlist] count]];
    CGSize size = [indexStr sizeWithFont:[UIFont systemFontOfSize:14] forWidth:999 lineBreakMode:NSLineBreakByCharWrapping];
    CGRect rect = focusButton.frame;
    rect.size.width = size.width + 10;
    rect.origin.x = 320 - 3 - rect.size.width;
    focusButton.frame = rect;
    [focusButton setTitle:indexStr forState:UIControlStateNormal];
}

- (IBAction)focus:(id)sender
{
    [playingTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[[AudioPlayer defaultPlayer] playingIndex] inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (void)updatePlayerProgress:(NSNotification *)notification
{
    if (playSlideView.tracking) {
        return;
    }
    AudioProgress *progress = (AudioProgress *)notification.object;
    length = progress.lenght;
    position = progress.position;
    if (progress.lenght > 0) {
        playSlideView.value = progress.position / progress.lenght;
        playedTimeLabel.text = [self stringFromSeconds:(int)progress.position];
        remainTimeLabel.text = [NSString stringWithFormat:@"-%@",[self stringFromSeconds:(int)(progress.lenght-progress.position)]];
    }
}

- (NSString *)stringFromSeconds:(int)seconds
{
    int hour = seconds / 3600;
    int minute = seconds % 3600 / 60;
    int second = seconds % 60;
    if (hour > 0) {
        return [NSString stringWithFormat:@"%2d:%02d:%02d",hour,minute,second];
    }
    else {
        return [NSString stringWithFormat:@"%02d:%02d",minute,second];
    }
}

- (void)updatePlayModeButton
{
    switch ([[AudioPlayer defaultPlayer] playerMode]) {
        case AudioPlayerModeAllLoop:
            [modeButton setImage:[UIImage imageNamed:@"playmode_all_loop"] forState:UIControlStateNormal];
            break;
        case AudioPlayerModeSingleLoop:
            [modeButton setImage:[UIImage imageNamed:@"playmode_one_loop"] forState:UIControlStateNormal];
            break;
        case AudioPlayerModeRandom:
            [modeButton setImage:[UIImage imageNamed:@"playmode_random"] forState:UIControlStateNormal];
            break;
        default:
            break;
    }
}

- (IBAction)navBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [playingTableView release];
    [_playingArray release];
    [playButton release];
    [playSlideView release];
    [playedTimeLabel release];
    [remainTimeLabel release];
    [lastButton release];
    [nextButton release];
    [modeButton release];
    [focusButton release];
    [titleLabel release];
    [super dealloc];
}
- (void)viewDidUnload {
    [playingTableView release];
    playingTableView = nil;
    [playButton release];
    playButton = nil;
    [playSlideView release];
    playSlideView = nil;
    [playedTimeLabel release];
    playedTimeLabel = nil;
    [remainTimeLabel release];
    remainTimeLabel = nil;
    [lastButton release];
    lastButton = nil;
    [nextButton release];
    nextButton = nil;
    [modeButton release];
    modeButton = nil;
    [focusButton release];
    focusButton = nil;
    [titleLabel release];
    titleLabel = nil;
    [super viewDidUnload];
}
@end
